package com.kevin.hw.zklock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author: kevin
 * @date: 2017/8/14
 * @description:
 */
public class ZookeeperClient {

    private final static String CONNECT_STRING = "localhost:2181";

    private static int sessionTimeout = 5000;


    public static ZooKeeper getInstance() throws IOException, InterruptedException {

        final CountDownLatch countDownLatch = new CountDownLatch(1);

        ZooKeeper zookeeper = new ZooKeeper(CONNECT_STRING, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if(Event.KeeperState.SyncConnected == watchedEvent.getState()){

                    countDownLatch.countDown();

                }
            }
        });
        countDownLatch.await();

        return zookeeper;

    }

    public static int getSessionTimeout(){
        return sessionTimeout;
    }
}
